<template>
	<view class="custom_move">
		<!-- @longpress="showHandle" -->
		<map id="myMap" scale="15" :longitude="longitude" :latitude="latitude" :enable-poi="true" class="map" :style="mapStyle" :polyline="polyline" :markers="markers">
			<!-- <image class="location" src="../../static/workbench/location.png" @tap="returnLocationHandle()" /> -->
		</map>
		<view class="panel" v-show="infoStatus">
			<view class="info">
				<view class="label">剩余</view>
				<view class="value">{{ distance }}公里</view>
				<view class="label">，预计</view>
				<view class="value">{{ duration }}分钟</view>
				<!-- <view class="more" @tap="moreHandle">订单详情</view> -->
			</view>
			<!-- <view class="opt"> -->
			<!-- <button class="cancel-btn" :style="cancelStyle">取消订单</button> -->
			<!-- <button class="confirm-btn" v-if="status == 2 || status == 3" @tap="driverArriviedHandle">司机到达</button> -->
			<!-- </view> -->
		</view>
	</view>
</template>

<script>
let QQMapWX = require('../../lib/qqmap-wx-jssdk.min.js');
let qqmapsdk;
export default {
	data() {
		return {
			orderId: null,
			status: null,
			mode: null,
			cancelStyle: '',
			map: null,
			mapStyle: '',
			startLatitude: 0,
			startLongitude: 0,
			endLatitude: 0,
			endLongitude: 0,
			latitude: 0,
			longitude: 0,
			targetLatitude: 0,
			targetLongitude: 0,
			distance: 0,
			duration: 0,
			polyline: [],
			markers: [],
			timer: null,
			infoStatus: true,
			messageTimer: null,
			orderTimer: null
		};
	},

	methods: {
		
		returnLocationHandle() {
			// console.log(`触发点击事件了`,this.map)
			this.map.moveToLocation();
		},
		
		formatPolyline(polyline) {
			let coors = polyline;
			let pl = [];
			//坐标解压（返回的点串坐标，通过前向差分进行压缩）
			const kr = 1000000;
			for (let i = 2; i < coors.length; i++) {
				coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
			}
			//将解压后的坐标放入点串数组pl中
			for (let i = 0; i < coors.length; i += 2) {
				pl.push({
					longitude: coors[i + 1],
					latitude: coors[i]
				});
			}
			return pl;
		},

		calculateLine() {
			// console.log(`开始点是:`, this.latitude, this.longitude);
			if (this.latitude == 0 || this.longitude == 0) {
				return;
			}
			qqmapsdk.direction({
				mode: this.mode,
				from: {
					latitude: this.latitude,
					longitude: this.longitude
				},
				to: {
					latitude: this.targetLatitude,
					longitude: this.targetLongitude
				},
				success: resp => {
					let route = resp.result.routes[0];
					let distance = route.distance;
					let duration = route.duration;
					let polyline = route.polyline;
					this.distance = Math.ceil((distance / 1000) * 10) / 10;
					this.duration = duration;

					let points = this.formatPolyline(polyline);

					this.polyline = [
						{
							points: points,
							width: 6,
							color: '#05B473',
							arrowLine: true
						}
					];
					
					this.markers = [
						{
							id: 1,
							latitude: this.latitude,
							longitude: this.longitude,
							width: 35,
							height: 35,
							anchor: {
								x: 0.5,
								y: 0.5
							},
							iconPath: '../../static/move/driver-icon.png'
						}
					];
				},
				fail: error => {
					console.log(error);
				}
			});
		},

		analyse() {
			// console.log('状态值是:', this.status);
			if (this.status == 2) {
				//已接单的状态
				let data = {
					orderId: this.orderId
				};
				this.ajax(
					this.url.searchOrderLocationCache,
					'POST',
					data,
					resp => {
						let result = resp.data.result;
						// console.log(`查询到的缓存结果是:`, result);
						if (result && result.hasOwnProperty('latitude') && result.hasOwnProperty('longitude')) {
							let latitude = result.latitude;
							let longitude = result.longitude;
							this.latitude = latitude;
							this.longitude = longitude;
							this.calculateLine();
						}
					},
					false
				);
			} else {
				this.calculateLine();
			}
		},

		//定时查询未支付的订单
		// queryUnPayOrder() {
		// 	if (this.messageTimer) {
		// 		clearInterval(this.messageTimer);
		// 		this.messageTimer = null;
		// 	}
		// 	this.messageTimer = setInterval(() => {
		// 		this.ajax(
		// 			this.url.receiveBillMessage,
		// 			'POST',
		// 			{},
		// 			resp => {
		// 				// console.log(`查询到的订单信息是:${resp.data.result}`);
		// 				if (resp.data.result == '您有代驾订单待支付') {
		// 					//清楚定时器,跳转到订单详情页面
		// 					clearInterval(this.messageTimer);
		// 					this.messageTimer = null;
		// 					uni.redirectTo({
		// 						url: '../order/order?orderId=' + this.orderId
		// 					});
		// 				} else if (resp.data.result == '您的代驾订单已完成') {
		// 					//清楚定时器,跳转到订单详情页面
		// 					clearInterval(this.messageTimer);
		// 					this.messageTimer = null;

		// 					uni.showToast({
		// 						icon: 'success',
		// 						title: '订单完成，请及时进行支付！'
		// 					});

		// 					setTimeout(() => {
		// 						//跳转到工作台界面
		// 						uni.switchTab({
		// 							url: '../workbench/workbench'
		// 						});
		// 					}, 1500);
		// 				}
		// 			},
		// 			false
		// 		);
		// 	}, 3000);
		// },

		//查询订单状态
		searchOrderStatus() {
			//先执行一遍,在开启定时器进行查询
			this.sendSearchOrderStatus()
			//先清空
			if (this.orderTimer) {
				clearInterval(this.orderTimer);
				this.orderTimer = null;
			}
			
			//3秒钟查询一下订单状态
			this.orderTimer = setInterval(() => {
				this.sendSearchOrderStatus()
			}, 3000);
		},
		
		//发送查询订单状态的请求
		sendSearchOrderStatus(){
			
			let data = {
				orderId: this.orderId
			};
			
			this.ajax(
				this.url.searchOrderStatus,
				'POST',
				data,
				resp => {
					// console.log(`轮巡查到的订单状态是:`,resp.data.result)
					if (resp.data.result == 3) {
						//司机已到达
						let data = {
							orderId: this.orderId
						};
						this.ajax(
							this.url.confirmArriveStartPlace,
							'POST',
							data,
							resp => {
								
								if (resp.data.result) {
									
									uni.showToast({
										icon: 'success',
										title: '司机已到达,即将进行代驾'
									});
									
									this.status = 4;
									this.mode = 'driving';
									this.targetLatitude = this.endLatitude;
									this.targetLongitude = this.endLongitude;
			
									//手动调用一下路线规划,用于立即处理出发地到目的地的位置
									this.analyse();
			
									//清除订单查询的定时器
									// clearInterval(this.orderTimer);
									// this.orderTimer = null;
									
									//查询订单状态
									// this.queryUnPayOrder();
								}
							},
							false
						);
					} else if (resp.data.result == 6) {
						//订单未付款
						//清楚定时器,跳转到订单详情页面
						clearInterval(this.orderTimer);
						this.orderTimer = null;
						uni.redirectTo({
							url: '../order/order?orderId=' + this.orderId
						});
					} else if (resp.data.result == 8) {
						//订单已结束
						//清楚定时器,跳转到订单详情页面
						clearInterval(this.orderTimer);
						this.orderTimer = null;
						
						uni.showToast({
							icon: 'success',
							title: '订单完成，请及时进行支付！'
						});
						
						setTimeout(() => {
							//跳转到工作台界面
							uni.switchTab({
								url: '../workbench/workbench'
							});
						}, 1500);
					}
				},
				false
			);
		},

		//进入页面时开始位置监听的方法
		initUpdateLocation() {
			
			//设置一下当前位置
			uni.getLocation({
				type: 'gcj02',
				// type: 'wgs84',
				success: res => {
					// console.log('定位的位置是:', res)
					this.latitude = res.latitude;
					this.longitude = res.longitude;
				}
			});

			//设置改变的监听
			uni.$on('updateLocation', location => {
				if (location != null && this.status != 2) {
					this.latitude = location.latitude;
					this.longitude = location.longitude;
				}
			});
		},

		//根据订单id查询订单
		searchOderById() {
			
			let that = this;
			let data = {
				orderId: that.orderId
			};

			that.ajax(that.url.searchOrderForMoveById, 'POST', data, resp => {
				let result = resp.data.result;
				// console.log(`查询结果是:`, result);
				let startPlaceLocation = JSON.parse(result.startPlaceLocation);
				that.startLatitude = startPlaceLocation.latitude;
				that.startLongitude = startPlaceLocation.longitude;

				//初始化地图的位置
				that.latitude = startPlaceLocation.latitude;
				that.longitude = startPlaceLocation.longitude;

				let endPlaceLocation = JSON.parse(result.endPlaceLocation);
				that.endLatitude = endPlaceLocation.latitude;
				that.endLongitude = endPlaceLocation.longitude;

				let status = result.status;

				//赋值状态
				that.status = status;

				// console.log('状态是:', that.status);

				if (status == 2) {
					//已接单
					that.targetLatitude = that.startLatitude;
					that.targetLongitude = that.startLongitude;
					that.mode = 'bicycling';
				} else if (status == 3 || status == 4) {
					//司机已到达 或者 开始代驾
					that.targetLatitude = that.endLatitude;
					that.targetLongitude = that.endLongitude;
					that.mode = 'driving';
				}

				//规划路线
				that.analyse(that);
				that.timer = setInterval(() => {
					that.analyse(that);
				}, 30000);

				// // if (status == 4 || status == 5) {
				// //开始代驾和结束代驾
				// if (status == 5) {
				// 	//结束代驾查询订单状态
				// 	this.queryUnPayOrder();
				// }
			});
		}
	},

	async onLoad(options) {
		let that = this;
		that.orderId = options.orderId;
		// console.log(`move界面传递到的订单ID是:`, options.orderId);
		// console.log(`move界面接收到的订单ID是:`, that.orderId);
		qqmapsdk = new QQMapWX({
			key: that.tencent.map.key
		});
		let windowHeight = uni.getSystemInfoSync().windowHeight;
		that.mapStyle = `height:${windowHeight}px`;

		that.map = uni.createMapContext('myMap', this);

		//设置位置更新的监听事件
		await this.initUpdateLocation();

		//根据订单id查询订单状态
		await this.searchOderById();

		//定时查询订单状态
		this.searchOrderStatus();
	},

	onShow() {},

	onHide() {
		uni.$off('updateLocation');
		clearInterval(this.timer);
		this.timer = null;
		clearInterval(this.messageTimer);
		this.messageTimer = null;
		clearInterval(this.orderTimer);
		this.orderTimer = null;
	},

	onUnload() {
		uni.$off('updateLocation');
		clearInterval(this.timer);
		this.timer = null;
		clearInterval(this.messageTimer);
		this.messageTimer = null;
		clearInterval(this.orderTimer);
		this.orderTimer = null;
	}
};
</script>

<style lang="less">
@import url('move.less');
</style>
